package com.coldchain.resource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@Controller
public class DowloadFileController {
	@Value("${update.dir}")
	private String updateDir;
	@GetMapping("/dowload")
	public void dowloadFile(
			@RequestParam("d") String dirName,
			@RequestParam("t") String filtType,
			@RequestParam("f") String fileName,
			HttpServletResponse response){
		InputStream in = null;
		ServletOutputStream sos=null;
		try {
			in = new FileInputStream(new File(
					updateDir
					.concat(File.separator)
					.concat(dirName)
					.concat(File.separator)
					.concat(filtType)
					.concat(File.separator)
					.concat(fileName)));
			BufferedImage buffImg=ImageIO.read(in);
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			response.setContentType("image/jpeg");
			sos=response.getOutputStream();
			ImageIO.write(buffImg,"jpeg",sos);
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				sos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}
}
